package com.example.birdfriends.controller;


import com.example.birdfriends.pojo.message.Message;
import com.example.birdfriends.pojo.message.MessageAndFriend;
import com.example.birdfriends.pojo.message.MessageVo;
import com.example.birdfriends.pojo.user.User;
import com.example.birdfriends.service.FollowService;
import com.example.birdfriends.service.MessageService;
import com.example.birdfriends.service.UserService;
import com.example.birdfriends.utils.convert.ConvertService;
import com.example.birdfriends.utils.message.MessageUtil;
import com.example.birdfriends.utils.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/msg")
public class MessageController {
    @Autowired
    private MessageService messageService;
    @Autowired
    private FollowService followService;
    @Autowired
    private UserService userService;
    @Autowired
    private Result result;

    @PostMapping("/friends")  // 消息页面显示用户好友列表，以及和好友的
    public Map<String, Object> findMyFriends(@RequestBody User user){
        Long curLoginUid = user.getId();
        System.out.print("当前登录用户：");user.printUser();

        Map<String, Object> friendMap = findCurLoginUserFriends(curLoginUid);  // 当前登录的用户的好友
        boolean success = (boolean)friendMap.get("success");
        if (success){
            // 查找最新消息：一个用户同好友之间的消息应该有多条，好友列表需要展示左心的一条
            List<User> friends = (List<User>) friendMap.get("object");  // 好友列表

            if (friends.isEmpty()){
                return result.resultMap(false, (String) friendMap.get("message"), friends);
            }

            List<MessageAndFriend> messageAndFriends = new ArrayList<>();
            for(User friend: friends){
                Long friendId = friend.getId();
                // 当前用户发给好友的消息
                List<Message> mySendMessages = messageService.findMessagesBySidAndRid(curLoginUid, friendId);  // 通过当前用户和他的好友id查找他们的消息列表
                // 好友发给当前用户的消息
                List<Message> myReceiveMessages = messageService.findMessagesBySidAndRid(friendId, curLoginUid);

                MessageAndFriend messageAndFriend = new MessageAndFriend();
                Message latestMsg;
                friend.setPassword("");
                messageAndFriend.setSender(friend);
                int unReadNumber = 0;
                if (mySendMessages.size() > 0 || myReceiveMessages.size() > 0){
                    // 好友之间有消息
                    List<Message> messages = messageUtil.mergeMessageList(mySendMessages, myReceiveMessages); // 和一个朋友的消息列表
                    latestMsg = messages.get(messages.size()-1);
                    unReadNumber = messageService.countUnReadMsgs(curLoginUid, friendId);
                }else {
                    latestMsg = new Message();
                    latestMsg.setMsg("你们已经是好友了，快来聊天吧");
                    latestMsg.setCreateAt(new Timestamp(System.currentTimeMillis()));
                }
                MessageVo latestMessageVo = convertService.message2MessageVo(latestMsg, "friends");  // 最新的消息
                messageAndFriend.setMessageVo(latestMessageVo);
                messageAndFriend.setUnReadMsgNumber(unReadNumber);
                messageAndFriends.add(messageAndFriend);
            }

            return result.resultMap(true, "查询成功", messageAndFriends);
        }

        return friendMap;
    }

    @Autowired
    private ConvertService convertService;
    @Autowired
    private MessageUtil messageUtil;

    // 查询当前登录用户的好友
    private Map<String, Object> findCurLoginUserFriends(Long curLoginUid){
        List<Long> myFollowUids = followService.findFollowedUidsByCurUid(curLoginUid);  // 查询我关注的用户的id
        List<User> friends = new ArrayList<>();
        for(Long followedUid: myFollowUids){
            // 如果followedUid作为当前进行关注者，curLoginUid作为被followed关注的用户存在
            Long fid = followService.findFidByCurUidAndFollowedUid(followedUid, curLoginUid);
            boolean isFriend = fid != null && fid > 0;
            if (isFriend){
                friends.add(userService.findUserByUid(followedUid));  // 好友列表
            }
        }

        boolean success = !friends.isEmpty();  // 找到了好友
        if(success){
            return result.resultMap(true, "查询好友成功", friends);
        }
        return result.resultMap(false, "还没有好友，快去添加好友吧。", friends);
    }

    @PostMapping("findMessagesInChat")
    public Map<String, Object> findWeMessages(@RequestBody MessageVo messageVo){
        Long curLoginUid = messageVo.getSenderId();  // 当前登录用户id
        Long friendId = messageVo.getReceiverId();  // 好友id
        String curPage = "chat";

        List<Message> mySend = messageService.findMessagesBySidAndRid(curLoginUid, friendId);
        List<Message> myReceive = messageService.findMessagesBySidAndRid(friendId, curLoginUid);
        List<Message> messages = messageUtil.mergeMessageList(mySend, myReceive);

        if (messages.isEmpty()){
            return result.resultMap(false, "还未有消息沟通", null);
        }

        List<MessageAndFriend> messageAndFriends = new ArrayList<>();
        for(Message message: messages){
            MessageAndFriend messageAndFriend = new MessageAndFriend();
            User sender = userService.findUserByUid(message.getSenderId());
            sender.setPassword("");
            messageAndFriend.setSender(sender);
            messageAndFriend.setMessageVo(convertService.message2MessageVo(message, curPage));
            messageAndFriends.add(messageAndFriend);
        }
        return result.resultMap(true, "查询消息成功", messageAndFriends);
    }
}
